<?php
namespace App\Admin\Actions;

use Dcat\Admin\Actions\Action;
use Illuminate\Http\Request;
use App\Models\SwitchModel;

class AllOperation extends Action
{
    protected $style = 'btn btn-white';

    public function __construct($level = 0, $op = 'off')
    {
        $this->level = $level;
        $this->op = $op;
    }

    public function title()
    {
        $levelTextArr = ['1' => '一级', '2' => '二级', '3' => '三级'];
        $levelText = $levelTextArr[$this->level];
        $opTextArr = ['on' => '开', 'off' => '关'];
        $opText = $opTextArr[$this->op];

        return '<button data-action="refresh" class="btn btn-primary grid-refresh btn-mini btn-outline" style="margin-right:3px"><span class="d-none d-sm-inline">&nbsp; '.$levelText.'全'.$opText.'</span></button>';
    }

    public function confirm()
    {
        if ($this->op == 'on') {
            $msg = '您确定要将所有开关全部开启吗？';
        } elseif ($this->op == 'off') {
            $msg = '您确定要将所有开关全部关闭吗？';
        }
        return [$msg, ''];
    }

    public function handle(Request $request) 
    {
        $level = $request->get('level');
        $op = $request->get('op');
        $pid = $this->getKey();
        $parent = SwitchModel::find($pid);
        $switches = SwitchModel::where('pid', $pid)->whereNotNull('machine_code')->where('level', $level)->get();

        foreach ($switches as $one) {
            if ($op == 'on') {
                SwitchModel::setSwitchOn($parent['machine_code'], $one['id'], $one['phase'], $one['machine_code']);
            } elseif ($op == 'off') {
                SwitchModel::setSwitchOff($parent['machine_code'], $one['id'], $one['phase'], $one['machine_code']);
            }
            sleep(1);
        }
        return $this->response()->success('成功！');
    }

    public function parameters()
    {
        return [
            'level' => $this->level,
            'op' => $this->op
        ];
    }
}